#!/usr/bin/env python
#coding=utf-8
# Copyrignt (c) xuzeshui.com. All Rights Reserved.
# Author: Zeshui Xu<i@xuzeshui.com>
# Created Time: 2015-11-15 17:04:06
# Last Modified: 2015-11-15 20:18:48
# File Name: avatar_upload.py
# Description: 

__version__ = "0.1"
__all__ = []

import os
import sys
import base64
import hashlib
import httplib
import time
import json

host = "127.0.0.1:8081"
appkey = "ff983cecc76d406a8b1c7c3c1b7cd172"
uid = "73524eb6c59447db86c35bdeaee1ef80"
ak = "be7939b4efb74b7087df0636ba44afe8"

def calc_url_sign(urlParams):
    keys = urlParams.keys()
    keys.sort()
    r = []
    for key in keys:
        r.append(key)
        r.append(str(urlParams[key]))
    r.append("passport.app.doubimeizhi.com")
    signstr = "".join(r)
    m = hashlib.md5()
    m.update(signstr)
    return m.hexdigest()

def get_qs(urlParams):
    qs = []
    for key, val in urlParams.iteritems():
        qs.append("%s=%s" % (key, val))
    return "&".join(qs)

def parse_host():
    r = host.split(":")
    return r[0], int(r[1])

def main():
    picData = open("1.jpg", "r").read()
    base64PicData = base64.b64encode(picData)
    body = {
        "avatar": base64PicData
    }
    urlParams = {
        "appkey": appkey,
        "ak": ak,
        "uid": uid,
        "time": int(time.time())
    }
    urlParams["sign"] = calc_url_sign(urlParams)
    uri = "/v1/user/avatar-base64/upload?%s" % get_qs(urlParams)
    ip, port = parse_host()
    conn = httplib.HTTPConnection(ip, port, timeout = 10)
    conn.request("POST", uri, json.dumps(body))
    resp = conn.getresponse()
    print resp.read()


if __name__  == "__main__":
    main()
